package com.zoweunion.mechanic.im;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.zoweunion.mechanic.dao.app.ImDao;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.plugins.redis.RedisUtil;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.UuidUtil;

@Service
public class ImService {

	@Autowired
	private ImConfig imConfig;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private ImDao imDao;

	public static final String IM_PRE = "IM_PRE:";
	public static final long EXPIRE_TIME = 3600 * 24;

	@SuppressWarnings("unchecked")
	public Map<String, Object> getToken(User user) throws MyException {
		Map<String,String> map = new HashMap<String, String>();
		Map<String, Object> resultMap = new HashMap<>();
		String nonce = UuidUtil.get32UUID();
		String signTimestamp = String.valueOf(System.currentTimeMillis());
		String signature = "";
		map.put("userId", user.getId());
		map.put("name", user.getUser_name());
		String u_id = user.getId();
		String result = "";
		try {
			signature = shaEncode(imConfig.getAppSecret()+nonce+signTimestamp);		
			if (redisUtil.get(IM_PRE+u_id+"token") == null) {
				result = HttpClient.send(imConfig.getUrl(), map, imConfig.getEncoding(), imConfig.getAppKey(), nonce, signTimestamp, signature);
				resultMap = JSONObject.parseObject(result,Map.class);
				String code = resultMap.get("code").toString();
				Object object = resultMap.get("token");
				if ("200".equals(code)) {
					
					int a = imDao.updateUserToken(object.toString(),u_id);
					
					if (a != 1) {
						
						throw new MyException(Constants.CODE_HANDEL_FAILED,"业务操作失败");
						
					}
					
					redisUtil.set(IM_PRE+u_id+"token",object,EXPIRE_TIME);
					return resultMap;

				}else {

					throw new MyException(Constants.CODE_HANDEL_FAILED,"业务操作失败");
				}
				
			}else {
				String token = redisUtil.get(IM_PRE+u_id+"token").toString();
				resultMap.put("token", token);
				return resultMap;
				
			}

		} catch (Exception e) {

			throw new MyException(Constants.CODE_HANDEL_FAILED,"业务操作失败");

		}

	}


	public static String shaEncode(String inStr) throws Exception {
		MessageDigest sha = null;
		try {
			sha = MessageDigest.getInstance("SHA");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}

		byte[] byteArray = inStr.getBytes("UTF-8");
		byte[] md5Bytes = sha.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}
}
